package com.jz.digital.database;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据库升级策略,只需要填写上一个版本的数据到这个版本的数据处理逻辑
 */
public class DatabaseUpgradeUtil {
    private static Map<String, UpgrateDataBase> mUpgradeMap = new HashMap<>();

    /**
     * 如果数据库升级请在这里注册
     */
    static {
    }

    public static boolean upgradeDatabase(StandardDatabaseWraper db, int oldVersion, int newVersion) {
        if (db == null) return false;
        if (oldVersion >= newVersion) return true;
        boolean result = false;
        while (oldVersion < newVersion) {
            String dataKey = getDatabaseUpgradeKey(oldVersion, ++oldVersion);
            if (mUpgradeMap.containsKey(dataKey)) {
                UpgrateDataBase upgrateDataBase = mUpgradeMap.get(dataKey);
                if (upgrateDataBase != null) {
                    result = upgrateDataBase.processUpgrade(db);
                    if (!result) {
                        break;
                    }
                }
            } else {
                result = true;
            }
        }
        return result;
    }

    /**
     * 获取数据库升级Key
     */
    private static String getDatabaseUpgradeKey(int oldVersion, int newVersion) {
        return oldVersion + "-" + newVersion;
    }

    public interface UpgrateDataBase {
        boolean processUpgrade(StandardDatabaseWraper db);
    }
}
